package com.atguigu.lease.web.admin.custom.interceptor;

import com.atguigu.lease.common.context.LoginUserContex;
import com.atguigu.lease.common.exception.MyAssert;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.minio.credentials.Jwt;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
@Component
public class AuthenticationIntercetor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String accessToken = request.getHeader("access_token");
        MyAssert.hasText(accessToken, "access_token不能为空");
        //解析token
        Claims claims = JwtUtil.parseToken(accessToken);
        Long userId = claims.get("userId", Long.class);
        String userName = claims.get("username", String.class);
        HashMap<String, String> tokenMap = new HashMap<>();
        tokenMap.put("userId", userId.toString());
        tokenMap.put("username", userName);
        System.out.println("========================================================");
        System.out.println("tokenMap = " + tokenMap);


        LoginUserContex.setUser(tokenMap);
        return true;
    }
}
